
export type HttpResultCallback = (msg: string, data: any) => void;

export default class HttpHelper {

    static sendHttpRequest(address: string, data: any, callback: HttpResultCallback, method: string = "GET") {
        console.log('sendHttpRequest  address ',address)
        let xhr = new XMLHttpRequest();
        xhr.timeout = 15000;
        xhr.ontimeout = function () {
            callback('ontimeout ', null)
        }
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 400) {
                var data = xhr.responseText;
                callback(null, data)
            } else {
                callback('onload error ', null)
            }
        };
        if (method == 'GET') {
            address = address + "?" + data;
            xhr.open(method, address);
            try {
                xhr.send();
            } catch (error) {
                callback('get error ' + error, null)
            }

        } else {
            // post请求
            xhr.open(method, address);
            try {
                xhr.send(data);
            } catch (error) {
                callback('POST error ' + error, null);
            }

        }
    }
}